#!/bin/bash

LIB="$(realpath $(dirname $0))"  # Absolute path
PROJ="$(dirname $LIB)"           # Game dir (..)
SRC="$PROJ"/../my_changes/          # My changes dir
DST="$PROJ"/mods/                # Game mods dir
#echo $LIB
#echo $PROJ
#echo $SRC
#echo $DST


#copy files
MOD_PATH=("player/skinsdb" "gui/smart_inventory")    #temporary not used: "minetest_game"

for MOD_INDEX in ${!MOD_PATH[*]}
do
	SRC_DIR="$SRC${MOD_PATH[MOD_INDEX]}/"
	DST_DIR="$DST${MOD_PATH[MOD_INDEX]}/"

	echo "---------------------------------------------------------------"
	echo "Syncing ${MOD_PATH[MOD_INDEX]} mod changes."
	echo "$SRC_DIR --> $DST_DIR"

	rsync -r -v --quiet $SRC_DIR $DST_DIR
	echo "---------------------------------------------------------------"
done

#patch code

#MOD_PATH=("mobs/water_life" "buildings/doors" "player/3d_armor" "player/hbsprint" "player/hunger_ng")
#MOD_PATCH=("poison.patch" "doors_update.patch" "mob_damage.patch" "no_damage.patch" "effects.patch")

#MOD_PATH and MOD_PATCH arrays for later
MOD_PATH=( )	#pathes to the patches
MOD_PATCH=( )	#patch names

#MOD_PATCHES - all patches defined
#MOD_PATCHES -  first is path and all patch names are separeted by ":"
#MOD_PATCHES=("mobs/water_life:poison.patch" "buildings/doors:doors_update.patch" "player/3d_armor:mob_damage.patch" "player/hbsprint:no_damage.patch" "player/hunger_ng:effects.patch")
MOD_PATCHES=("buildings/doors:doors_update.patch" "player/hbsprint:no_damage.patch" "environment/dynamic_liquid:bucket.patch" "mobs/water_life:poison.patch" "mobs/water_life:poison_hunger_ng.patch")
#MOD_PATCHES=( )

echo "---------------------------------------------------------------"
echo "DEFINED PATCHES"
echo
for PATCH_MOD in ${MOD_PATCHES[@]}; do
	echo $PATCH_MOD
	IFS=':' #  : is set as delimiter
	read -ra ADDR <<< "${PATCH_MOD}" # str is read into an array as tokens separated by IFS
	for i in "${!ADDR[@]}"; do # access each element of array
		#echo ${ADDR[i]}
		#0 is patch, patch names are index 1 and greather
		if [ $i -gt 0 ];	then
			PATCH_INDEX=${#MOD_PATCH[@]}
			MOD_PATH+=(${ADDR[0]})
			MOD_PATCH+=(${ADDR[i]})
			echo "$PATCH_INDEX: ${MOD_PATH[PATCH_INDEX]} / ${MOD_PATCH[PATCH_INDEX]}"
		fi
	done
	echo
	IFS=' ' # reset to default value after usage
done
echo "---------------------------------------------------------------"

#Use all patches
for MOD_INDEX in ${!MOD_PATH[*]}
do
	SRC_DIR="$SRC${MOD_PATH[MOD_INDEX]}/"
	DST_DIR="$DST${MOD_PATH[MOD_INDEX]}/"

	echo "---------------------------------------------------------------"
	echo "Apllying patch to ${MOD_PATH[MOD_INDEX]}."
	echo

	cd $DST_DIR

	patch -p1 < "$SRC_DIR/${MOD_PATCH[MOD_INDEX]}"

	echo "---------------------------------------------------------------"
done
